package com.yimi.yinhepda.views.offline.unload;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.db.dao.ScanDetailVoDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.ScanDetailVo;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 离线卸车撤销界面
 * Created by 000432
 *
 * @author Administrator
 */

public class OffLineUnloadDeleteActivity extends BaseActivity implements View.OnClickListener {

    private TextView num;
    private EditText mInputChildWayBill;
    private Button mDelBtn;
    private ListView mListView;
    private Button mdelOk;
    private TextView mDeleteCount;
    /**
     * 卸车标志
     */
    private int operTypeCode = 4;
    private String userCode;
    private UnloadScanTableDao mUnloadScanTableDao;
    private ScanDetailVoDao scanDetailVoDao;
    private UnloadTaskTableDao taskTableDao;
    /**
     * 离线任务号
     */
    private String offlineTaskNo;
    private List<ScanDetailVo> scanList;
    /**
     * 配载单对象
     */
    private UnloadTaskTable taskTable;
    private DeleteScanedAdapter adapter;
    private ArrayList<DeleteEntity> deleteEntityLists = new ArrayList<>();

    public OffLineUnloadDeleteActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_backout);

        initView();
        initEvent();
        initData();
    }

    @Override
    public String getPageName() {
        return "手动删除单号";
    }

    public void initView() {
        num = findViewById(R.id.num);
        TextView mTitle = findViewById(R.id.title);
        mInputChildWayBill = findViewById(R.id.load_delchildwaybill_ed);
        mDelBtn = findViewById(R.id.manual_del_btn);
        mListView = findViewById(R.id.del_chidlwaybill_listview);
        mdelOk = findViewById(R.id.del_childwaybill_ok);
        mDeleteCount = (TextView) findViewById(R.id.manaul_del_count);
        mTitle.setText("手动删除单号");
    }

    public void initEvent() {
        mDelBtn.setOnClickListener(this);
        mdelOk.setOnClickListener(this);
    }

    public void initData() {
        mUnloadScanTableDao = new UnloadScanTableDao();
        scanDetailVoDao = new ScanDetailVoDao();
        taskTableDao = new UnloadTaskTableDao();

        userCode = sharedPreferUtil.getValue(Common.USER_CODE);

        offlineTaskNo = getIntent().getStringExtra("offlineTaskNo");
        if (offlineTaskNo == null) {
            offlineTaskNo = "";
        }
        scanList = scanDetailVoDao.getDataByStowageAndType(offlineTaskNo, operTypeCode, userCode);
        if (scanList == null) {
            scanList = new ArrayList<>();
        }
        List<UnloadTaskTable> stowage = taskTableDao.findStowage(offlineTaskNo, userCode);
        if (stowage != null && !stowage.isEmpty()) {
            taskTable = stowage.get(0);
        }

        adapter = new DeleteScanedAdapter(this, deleteEntityLists);
        mListView.setAdapter(adapter);
        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            mInputChildWayBill.setText(result);
            doScan(result);
        }
    }

    /**
     * 处理扫描
     */
    protected void doScan(String result) {
        //判断是否是主单号
        boolean isMasterWaybillNo = StringUtils.isMasterWayBillNo(result);

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result) && !isMasterWaybillNo) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!");
            return;
        }

        //判断运单是否存在
        boolean isExitWayBillNo = false;
        if (isMasterWaybillNo) {
            //撤销主单号
            //判断主单中的子单是否已扫
            List<UnloadScanTable> childWaybillNo = mUnloadScanTableDao.getChildWaybillNoByWaybill(offlineTaskNo, operTypeCode, userCode, result);
            if (childWaybillNo == null || childWaybillNo.isEmpty()) {
                SoundVibratorManager.playSound(2);
                showToast("运单未扫描！");
                return;
            }
            if (scanList != null && !scanList.isEmpty()) {
                for (ScanDetailVo scanDetailVo : scanList) {
                    if (scanDetailVo.getWaybillNo().equals(result)) {
                        isExitWayBillNo = true;
                        int count = 0;
                        try {
                            taskTable.setPriceNum(taskTable.getPriceNum() - 1);
                            taskTableDao.update(taskTable);
                            scanDetailVoDao.delete(scanDetailVo);
                            for (UnloadScanTable unloadScanTable : childWaybillNo) {
                                count++;
                                mUnloadScanTableDao.delete(unloadScanTable);
                            }
                        } catch (SQLException e) {
                            LogUtil.e(e.toString());
                        }
                        boolean isExist = false;
                        for (DeleteEntity item : deleteEntityLists) {
                            if (item.getWaybill().equals(scanDetailVo.getWaybillNo())) {
                                item.setScanedwaybillsNum("0");
                                item.setCancelwaybillsNum((count + Integer.parseInt(item.getCancelwaybillsNum())) + "");
                                deleteEntityLists.remove(item);
                                deleteEntityLists.add(0, item);
                                isExist = true;
                                break;
                            }
                        }
                        if (!isExist) {
                            DeleteEntity mDeleteEntity = new DeleteEntity();
                            mDeleteEntity.setWaybill(scanDetailVo.getWaybillNo());
                            mDeleteEntity.setScanedwaybillsNum("0");
                            mDeleteEntity.setCancelwaybillsNum(count + "");
                            deleteEntityLists.add(mDeleteEntity);
                        }
                        break;
                    }
                }
            }
        } else {
            //撤销子单号
            //判断子单是否已扫
            List<UnloadScanTable> childWaybillNo = mUnloadScanTableDao.getChildWaybillNo(offlineTaskNo, operTypeCode, userCode, result);
            if (childWaybillNo == null || childWaybillNo.isEmpty()) {
                SoundVibratorManager.playSound(2);
                showToast("运单未扫描！");
                return;
            }
            String wayBillNo = result.substring(0, 12);
            if (scanList != null && !scanList.isEmpty()) {
                for (ScanDetailVo scanDetailVo : scanList) {
                    if (scanDetailVo.getWaybillNo().equals(wayBillNo)) {
                        isExitWayBillNo = true;
                        //更新数据库
                        scanDetailVo.setQuantity(scanDetailVo.getQuantity() - 1);
                        scanDetailVo.setScanTime(DateHelper.getDateFormateOffline());
                        try {
                            //删除运单
                            UnloadScanTable unloadScanTable = childWaybillNo.get(0);
                            taskTable.setPiecesNum(taskTable.getPiecesNum() - 1);
                            if (scanDetailVo.getQuantity() == 0) {
                                taskTable.setPriceNum(taskTable.getPriceNum() - 1);
                                scanDetailVoDao.delete(scanDetailVo);
                                taskTableDao.update(taskTable);
                            } else {
                                scanDetailVoDao.update(scanDetailVo);
                                //更新配载单件数
                                taskTableDao.update(taskTable);
                            }
                            mUnloadScanTableDao.delete(unloadScanTable);
                        } catch (SQLException e) {
                            LogUtil.e(e.toString());
                        }
                        boolean isExist = false;
                        for (DeleteEntity item : deleteEntityLists) {
                            if (item.getWaybill().equals(scanDetailVo.getWaybillNo())) {
                                item.setCancelwaybillsNum((Integer.parseInt(item.getCancelwaybillsNum()) + 1) + "");
                                item.setScanedwaybillsNum((Integer.parseInt(item.getScanedwaybillsNum()) - 1) + "");
                                isExist = true;
                                break;
                            }
                        }
                        if (!isExist) {
                            DeleteEntity mDeleteEntity = new DeleteEntity();
                            mDeleteEntity.setWaybill(scanDetailVo.getWaybillNo());
                            mDeleteEntity.setScanedwaybillsNum(scanDetailVo.getQuantity() + "");
                            mDeleteEntity.setCancelwaybillsNum("1");
                            deleteEntityLists.add(mDeleteEntity);
                        }
                        break;
                    }
                }
            }
        }

        if (!isExitWayBillNo) {
            showToast("运单号未扫描！");
            SoundVibratorManager.playSound(2);
            return;
        }

        //更新显示信息
        adapter.notifyDataSetChanged();
        //设置总票，总件数
        if (deleteEntityLists != null) {
            excCount();
        }
        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
        SoundVibratorManager.playSound(1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.manual_del_btn:
                String childWayBill = mInputChildWayBill.getText().toString();
                if (TextUtils.isEmpty(childWayBill)) {
                    SoundVibratorManager.playSound(2);
                    showToast("请先输入需要手动添加的单号！");
                    return;
                }
                doScan(childWayBill);
                break;
            case R.id.del_childwaybill_ok:
                backMethod();
                break;
            default:
                break;
        }
    }

    private void backMethod() {
        Bundle bundle = new Bundle();
        bundle.putString("offlineTaskNo", offlineTaskNo);
        setResult(OffLineUnloadActivity.ADD_DELETE_RESULTOK, this.getIntent().putExtras(bundle));
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    //计算撤销的票件
    private void excCount() {
        int count = 0;
        for (DeleteEntity item : deleteEntityLists) {
            count += Integer.parseInt(item.getCancelwaybillsNum());
        }
        mDeleteCount.setText(deleteEntityLists.size() + "/" + count);
    }

    static class DeleteScanedAdapter extends BaseAdapter {
        private Context context;
        private List<DeleteEntity> dataList;

        public DeleteScanedAdapter(Context context, List<DeleteEntity> dataList) {
            this.context = context;
            this.dataList = dataList;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DeleteWayBillHolder mHolder;
            if (convertView == null) {
                mHolder = new DeleteWayBillHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.activity_del_scaned_waybillitem, null);
                mHolder.waybillno = (TextView) convertView.findViewById(R.id.cancelwaybill);
                mHolder.scanedwaybillNum = (TextView) convertView.findViewById(R.id.scanedwaybillnum);
                mHolder.cancelwayBillNum = (TextView) convertView.findViewById(R.id.canceledwaybillnum);

                convertView.setTag(mHolder);
            } else {
                mHolder = (DeleteWayBillHolder) convertView.getTag();
            }
            mHolder.waybillno.setText(dataList.get(position).getWaybill());
            mHolder.scanedwaybillNum.setText(dataList.get(position).getScanedwaybillsNum());
            mHolder.cancelwayBillNum.setText(dataList.get(position).getCancelwaybillsNum());

            return convertView;
        }
    }

    static class DeleteWayBillHolder {
        TextView waybillno;
        TextView scanedwaybillNum;
        TextView cancelwayBillNum;
    }

    static class DeleteEntity {
        private String waybill;// 运单号
        private String scanedwaybillsNum;// 已扫数量
        private String cancelwaybillsNum;// 撤销数量

        public String getWaybill() {
            return waybill;
        }

        public void setWaybill(String waybill) {
            this.waybill = waybill;
        }

        public String getScanedwaybillsNum() {
            return scanedwaybillsNum;
        }

        public void setScanedwaybillsNum(String scanedwaybillsNum) {
            this.scanedwaybillsNum = scanedwaybillsNum;
        }

        public String getCancelwaybillsNum() {
            return cancelwaybillsNum;
        }

        public void setCancelwaybillsNum(String cancelwaybillsNum) {
            this.cancelwaybillsNum = cancelwaybillsNum;
        }
    }
}
